package data

import (
	"net"
	"strings"

	Log "github.com/cihub/seelog"
	"github.com/gin-gonic/gin"
)

type IpUtil struct{}

//获取访问IP
func (this IpUtil) GetIP(ctx *gin.Context) string {
	ip := ctx.Request.Header.Get("X-Real-IP")
	if net.ParseIP(ip) != nil {
		return ip
	}

	ip = ctx.Request.Header.Get("X-Forward-For")
	for _, i := range strings.Split(ip, ",") {
		if net.ParseIP(i) != nil {
			return ip
		}
	}

	ip, _, err := net.SplitHostPort(ctx.Request.RemoteAddr)
	if err != nil {
		Log.Error("获取访问IP地址发生异常:", err) //使用localhost会得到这个IP
		return "0.0.0.0"
	}

	if net.ParseIP(ip) == nil {
		return ip
	}

	if "0:0:0:0:0:0:0:1" == ip {
		ip = "127.0.0.1"
	} else if "::1" == ip {
		ip = "127.0.0.1"
	}

	if "127.0.0.1" != ip {
		return ip
	}

	result, err := IpUtil{}.GetOutBoundIP()
	if err != nil {
		return ip
	}

	return result
}

//获取本机ip地址
func (this IpUtil) GetOutBoundIP() (ip string, err error) {
	conn, err := net.Dial("udp", "8.8.8.8:53")
	if err != nil {
		Log.Error("获取本地IP地址发生异常:", err)
		return
	}

	localAddr := conn.LocalAddr().(*net.UDPAddr)
	ip = strings.Split(localAddr.String(), ":")[0]

	return
}
